import React from "react";

const userContext = React.createContext({
  name: "默认名称",
  age: "默认年龄",
});

class MyChild2 extends React.Component {
  render() {
    // 步骤四：在render函数中使用this.context传递的数据
    console.log(this.context);
    return (
      <div>
        <hr />
        <h2>孩子嵌套组件</h2>
        <h2>Context获取数据：{this.context.name + "——" + this.context.age}</h2>
      </div>
    );
  }
}
// 步骤三：对类组件的contextType赋值
MyChild2.contextType = userContext;

class MyChild extends React.Component {
  render() {
    return (
      <div>
        <h1>孩子组件</h1>
        <MyChild2 />
      </div>
    );
  }
}

export default class ContextCpn extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "fsy",
      age: 21,
    };
  }
  render() {
    return (
      <div>
        ContextCCpn
        {/* 步骤二：使用userContext.Provider组件来包裹子组件，并给value赋值传递数据 */}
        <userContext.Provider value={this.state}>
          <MyChild />
        </userContext.Provider>
        {/* 如果没有被Provider包裹则在子组件中使用this.context会获取到默认值 */}
        <MyChild />
      </div>
    );
  }
}
